package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 计算每个频道的文章计算得分(定时前五天)
 */
@Slf4j
@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public void computeHotArticle() {
        //1. 查询前5天的 已上架且未删除 的文章数值
            // 获取当前时间前推5天,的日期格式 "yyyy-MM-dd 00:00:00"
            String date = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
            //根据mapper查询大于往前5天日期的时间
            List<ApArticle> articleList = apArticleMapper.selectList(
                    Wrappers.<ApArticle>lambdaQuery().gt(ApArticle::getPublishTime,date));
        // 2. 计算查询出的文章分值,封装进vo对象,进行返回
        List<HotArticleVo> hotArticleVoList = computeArticleScore(articleList);

        //3.根据频道缓存问文章
        cacheToRedisByTag(hotArticleVoList);
    }


    /**
     * 查询文章分值,stream流(遍历Volist,提取每个vo对象,调用方法计算分值)
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {
        //定义返回集合
        return articleList.stream().map(apArticle ->
        {
            HotArticleVo hotArticleVo = new HotArticleVo();
            //计算个别文章分数计算方法
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }


    /**
     * 定义方法
      * @param hotArticleVoList
     */
    private void cacheToRedisByTag(List<HotArticleVo> hotArticleVoList){
        //远程查询频道数据
        ResponseResult responseResult = adminFeign.selectAllChannel();
        // 解析全部频道列表
        List<AdChannel> channelList = JSONArray.parseArray(JSON.toJSONString(responseResult.getData()), AdChannel.class);

        //为每个分类频道,缓存所有数据的排行30的文章
        channelList.forEach(channel -> {
                    List<HotArticleVo> hotArticleByChannel = hotArticleVoList.stream()
                            .filter(articleVo -> articleVo.getChannelId().equals(channel.getId()))
                            .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                            .limit(30)
                            .collect(Collectors.toList());
            // 缓存当前频道文章
            cacheToRedis(hotArticleByChannel,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+channel.getId());
        });
        //为推荐频道(默认频道),缓存前30
                    List<HotArticleVo> hotArticleByAll = hotArticleVoList.stream()
                            .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                            .limit(30)
                            .collect(Collectors.toList());
                    cacheToRedis(hotArticleByAll,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

        /**
         * 缓存文章集合到redis中
         * @param hotArticleByChannel
         * @param cacheKey
         */
        private void cacheToRedis(List<HotArticleVo> hotArticleByChannel, String cacheKey) {
            redisTemplate.opsForValue().set(cacheKey,JSON.toJSONString(hotArticleByChannel));}




    /**
     * 计算得分
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;
        // 阅读 每次1分
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        // 点赞 每次3分
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 每次5分
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 每次8分
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
